<template>
  <div>
    <Portal to="right-disable" :disabled="!queryModelDefaultSetting.showSetting">
      <div class="dropdown">
        <el-card shadow="hover" v-if="gadgetSetting.show">
          <p style="margin-bottom: 10px">
            <span v-if="'' !== gadgetSetting.name" style="font-size: 16px; font-weight: 600">{{ gadgetSetting.name
            }}</span>
            <el-tooltip :open-delay="1000" class="item" effect="dark" :content="gadgetSetting.description"
              placement="right" v-if="'' !== gadgetSetting.description">
              <i class="cuifont icon_help_circle" style="margin-left: 5px"></i>
            </el-tooltip>
          </p>
          <div class="control-section">
            <div class="content-wrapper" v-loading="loading" style="width: 100%">
              <el-select v-model="value" filterable :placeholder="gadgetSetting.watermark" :disabled="disable" :popper-append-to-body="popperAppendToBody">
                <el-option v-for="(its, ii) in datesource" :key="ii" :label="its.text" :value="its.value"></el-option>
              </el-select>
            </div>
          </div>
        </el-card>
        <div class="control-section" :style="{ height: gadgetHeight + 'px' }" v-else>
          <div class="content-wrapper" v-loading="loading" style="width: 100%">
            <div class="dropdown-list-custom-css">
              
              <el-select v-model="value" @visible-change="onvisiblechange" @remove-tag="removeTag" :disabled="disable" :popper-append-to-body="popperAppendToBody"
                :multiple="ismultiplemode" @clear="clearSelect" :collapse-tags="ismultiplemode" clearable filterable
                :placeholder="gadgetSetting.watermark" :popper-class="this.fitToHeight?'dropdown-list-minwidth':''">
                <div v-if="ismultiplemode" @click="allHandler" class="cursor_pointer" style="
                    margin: 4px 20px 10px;
                    height: 28px;
                    color: #17b3a3;
                    background-color: rgba(19, 141, 199, 0.1);
                    border: 1px dashed #17b3a3;
                    border-radius: 4px;
                    text-algin: center;
                    line-height: 28px;
                  ">
                  <div style="display: flex; justify-content: center">
                    <span style="color: #17b3a3; font-size: 14px">{{
                        datesource.length === value.length
                          ? 'Clear All'
                          : 'Select All'
                    }}</span>
                  </div>
                </div>
                <el-option v-for="(its, ii) in datesource" :key="ii" :label="its.text" :value="its.value"></el-option>
              </el-select>
              <div class="dropdownpre" v-if="
                gadgetSetting.filterLabel &&
                gadgetSetting.filterLabel.length > 0
              ">
                {{ gadgetSetting.filterLabel }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </Portal>
    <model :showSetting="queryModelDefaultSetting.showSetting" @queryModelClosed="queryModelClosed"
      @queryModelPreview="queryModelPreview" :dataInfo="queryModelDefaultSetting.dataInfo"
      :updateGadget="upgradeGadgetSetting" :slicer="slicer" />
  </div>
</template>

<script>
import mixinGadgetViewModule from '@/mixins/gadget-view-module'
// import model from '@/components/gadget/query-model/query-model.vue'
import { defaultGadgetSettingList } from '@/utils/data-json'
import { debounce } from 'lodash'
import { sqlSet } from '@/components/storybook/utilties/throttleRequest'
import { queryURLParams, query } from '@/components/storybook/utilties/tools'
/* eslint-disable */
export default {
  mixins: [mixinGadgetViewModule],
  components: {
    model: () => import('@/components/gadget/query-model/query-model')
  },
  data: function () {
    return {
      datesource: {
        value: '100',
        text: '100'
      },
      gadgetSetting: {},
      value: null,
      ismultiplemode: false,
      gadgetStatus: 'init',
      loading: false,
      queryModelDefaultSetting: {
        showSetting: false,
        dataInfo: {
          businessId: this.pageId,
          gadgetId: this.id,
          gadgetSettingExclude: ['DATA'],
          gadgetType: 'dropdownlistgadget',
          gadgetSetting: this._.find(defaultGadgetSettingList, {
            gadgetType: 'dropdownlistgadget'
          }).gadgetSetting
          // gadgetSetting: {
          //   showClearButton: 'true',
          //   watermark: 'Select a Client',
          //   allowFiltering: true,
          //   filterPlaceholder: 'Search',
          //   fields: { text: 'text', value: 'value' },
          //   height: '220px',
          //   queryParams: 'tenantCode',
          //   show: false,
          //   name: '',
          //   description: ''
          // }
        }
      },
      heightoffset: 60,
      searchValue: null,
      disable: false
    }
  },
  beforeCreate() {
    // this.$options.components.model = () => import('@/components/gadget/query-model/query-model')
  },
  created() {
    this.query()
    this.$store.state.isWidget = false
    this.gadgetHeight = this.gadgetInfo.h * 20 - this.heightoffset - 36
  },
  activated() {
    // this.afterQuery()
  },
  destroyed() {
    this.delQueryParam()
  },
  methods: {
    resized(i, newH, newW, newHPx, newWPx) {
      this.gadgetHeight = newH * 20 - this.heightoffset - 36
      this.gadgetWidth = newWPx
    },
    allHandler() {
      if (this.datesource.length === this.value.length) {
        this.value = []
        // this.clearSelect()
      } else {
        var arr = []
        this.datesource.forEach(item => {
          arr.push(item.value)
        })
        this.value = arr
        this.searchValue = this.value
        // this.getDataListParams(arr)
      }
    },
    queryModelClosed() {
      this.queryModelDefaultSetting.showSetting = false
      this.query()
    },
    showQueryModel() {
      this.queryModelDefaultSetting.showSetting = true
    },
    query() {
      this.loading = true
      this._.merge(
        this.gadgetSetting,
        this.queryModelDefaultSetting.dataInfo.gadgetSetting
      )
      var _self = this
      var param = {
        pageId: this.pageId,
        gadgetId: this.id,
        code: this.code,
        gadgettype: this.wgadgettype,
        widgetName: this.wName
      }
      this.$interface.reports
        .getReportDataInfo(param)
        .then(({ data: res }) => {
          if (res.config) {
            _self._.merge(_self.gadgetSetting, res.config);
            // (this.pageFromType!=='report')&&(this.ismultiplemode = _self.gadgetSetting.multiplemode.some(
            //   item => item === 'Multiple mode'
            // ))
            this.ismultiplemode = _self.gadgetSetting.multiplemode.some(
              item => item === 'Multiple mode'
            )
          }
          if (res.data) {
            _self.heightoffset = 5
            _self.gadgetHeight =
              _self.gadgetInfo.h * 20 - _self.heightoffset - 15
            var tempList = []
            for (let index = 0; index < res.data.length; index++) {
              const element = res.data[index]
              try {
                tempList.push({
                  text: element[_self.gadgetSetting.fields.text],
                  value: element[_self.gadgetSetting.fields.value]
                })
              } catch (error) { }
            }
            _self.datesource = tempList
          }
          _self.afterQuery()
          // _self.updateGadgetStatus('ready') //! IMPORTANT must have this code in every gadget
          this.loading = false
        })
        .catch(() => {
          this.loading = false
        })
        .finally(() => {
          this.loading = false
          this.updateGadgetLoadingStatus(!this.loading)
        })
    },
    afterQuery() {
      let url
      if(!this.$route.fullPath.includes('shareToken')) {
        var valueFromQuery = this.$route.query[Array.isArray(this.gadgetSetting.queryParams)?this.gadgetSetting.queryParams[0]:this.gadgetSetting.queryParams]
        this.disable =query('disable', this.$route.query,false)
      } else {
        url = queryURLParams(decodeURIComponent(this.$route.fullPath))
        var valueFromQuery = query(this.gadgetSetting.queryParams,url)
        this.disable =query('disable', url,false)
      }
      if(this.disable==='true'){
        this.disable = true
      }
      if(this.disable==='false'){
        this.disable = false
      }
      
      if (valueFromQuery) {
        if (this.gadgetSetting.show) {
          this.ismultiplemode = false
          this.value = valueFromQuery
        } else {
          this.ismultiplemode = true
          this.value = [valueFromQuery]
        }
      } else {
        var saveSlicer = null
        if (window.location.search.includes('name=')) {
          saveSlicer = this.ismultiplemode
            ? JSON.parse(
                localStorage.getItem(
                  this.pageId +
                    '-dropdown-list-gadget-' +
                    this.gadgetSetting.queryParams
                )
              )
            : localStorage.getItem(
                this.pageId +
                  '-dropdown-list-gadget-' +
                  this.gadgetSetting.queryParams
              )
        } else {
          if (!window.location.search.includes('&')) {
            if (this.pageId) {
              saveSlicer = this.ismultiplemode
                ? JSON.parse(
                    localStorage.getItem(
                      this.pageId +
                        '-dropdown-list-gadget-' +
                        this.gadgetSetting.queryParams
                    )
                  )
                : localStorage.getItem(
                    this.pageId +
                      '-dropdown-list-gadget-' +
                      this.gadgetSetting.queryParams
                  )
            }
          }
        }
        if (saveSlicer) {
          if (this.ismultiplemode) {
            if (Array.isArray(saveSlicer)) {
              this.value = saveSlicer
            } else {
              this.value = [saveSlicer]
            }
          } else {
            this.value = saveSlicer
          }
          valueFromQuery = saveSlicer
        } else {
          if (this.ismultiplemode) {
            var arr = []
            this.datesource.forEach(item => {
              arr.push(item.value)
            })
            if (this.gadgetSetting.defaultSelected === '1') {
              this.value = [this.datesource[0].value]
              valueFromQuery = [this.datesource[0].value]
            } else {
              this.value = arr
              valueFromQuery = arr
            }
          } else {
            if (this.datesource.length) {
              this.value = this.datesource[0].value
                ? this.datesource[0].value
                : null
              valueFromQuery = this.datesource[0].value
                ? this.datesource[0].value
                : null
            }
          }
        }
      }
      this.searchValue = this.value
      this.getDataListParams(valueFromQuery)
    },
    onvisiblechange(e) {
      if (!e && this.value !== this.searchValue) {
        if (this.ismultiplemode && this.value.length === 1) {
          this.getDataListParams(this.value)
        } else {
          this.getDataListParams(this.value)
        }
        this.searchValue = this.value
      } else if (!e) {
        this.getDataListParams(this.value)
      }
      //  
      if(this.fitToHeight&&e) { 
        let str = document.querySelector('.dropdown-list-minwidth').style['minWidth'] 
        str=str.substring(0,str.length-2);
        document.querySelector('.dropdown-list-minwidth').style['minWidth'] = `${str * this.zoomNumber}px`
      } else if(this.fitToHeight&&!e){
         let str = document.querySelector('.dropdown-list-minwidth').style['minWidth'] 
        str=str.substring(0,str.length-2);
        document.querySelector('.dropdown-list-minwidth').style['minWidth'] = `${str / this.zoomNumber}px`
      }
    },
    removeTag(e) {
      if (this.value.length === 0) {
        var arr = []
        this.datesource.forEach(item => {
          arr.push(item.value)
        })
        this.value = [arr[0]]
      }
      this.searchValue = this.value
      this.getDataListParams(this.value)
    },
    onFiltering(e) {
      // get input data
    },
    clearSelect() {
      if (this.gadgetSetting.disableClear) {
        if (this.ismultiplemode) {
          var arr = []
          this.datesource.forEach(item => {
            arr.push(item.value)
          })
          this.value = [arr[0]]
        } else {
          this.value = this.datesource[0].value
            ? this.datesource[0].value
            : null
        }
        this.searchValue = this.value
        this.getDataListParams(this.value)
      } else {
        this.getDataListParams(null)
      }
    },
    getDataListParams(val) {
      var _self = this
      if (val) {
        sqlSet.clear()
        _self.slicer[_self.gadgetSetting.queryParams] = val
        if (window.location.search.includes('name=')) {
          let keyValue = _self.ismultiplemode ? JSON.stringify(val) : val
          localStorage.setItem(
            _self.pageId +
            '-dropdown-list-gadget-' +
            _self.gadgetSetting.queryParams,
            keyValue
          )
        } else {
          let keyValue = _self.ismultiplemode ? JSON.stringify(val) : val
          if (!window.location.search.includes('&')) {
            localStorage.setItem(
              _self.pageId +
              '-dropdown-list-gadget-' +
              _self.gadgetSetting.queryParams,
              keyValue
            )
          }
        }
      } else {
        delete _self.slicer[_self.gadgetSetting.queryParams]
        if (window.location.search.includes('name=')) {
          localStorage.removeItem(
            _self.pageId +
            '-dropdown-list-gadget-' +
            _self.gadgetSetting.queryParams
          )
        } else {
          if (!window.location.search.includes('&')) {
            localStorage.removeItem(
              _self.pageId +
              '-dropdown-list-gadget-' +
              _self.gadgetSetting.queryParams
            )
          }
        }
        _self.$message.error(_self.gadgetSetting.watermark)
      }

      this.updateGadgetStatus('ready')
    },
    activedAfterQuery: debounce(function () {
      var _self = this
      _self.updateGadgetStatus('ready')
    }, 0),
    delQueryParam () {
      if (!this.$route.path.includes('/bot-')) {
        delete this.slicer[this.gadgetSetting.queryParams]
      }
    },
  }
}
</script>
<style scoped>
/* .el-card ::v-deep .el-card__body {
  padding: 5px 5px !important;
}
.el-card ::v-deep .el-divider--horizontal {
  margin: 3px 0 !important;
} */
.cursor_pointer {
  cursor: pointer;
}
</style>
<style lang="scss">
.dropdown-list-custom-css {
  position: relative;
  width: 100%;
  display: flex;
  flex-direction: row-reverse;

  .el-select__tags-text {
  max-width: 80px !important;

  }

  .dropdownpre {
    padding: 0 15px;
    border-right: none;
    display: flex;
    align-items: center;
    border-top-left-radius: 4px;
    border-bottom-left-radius: 4px;
  }

  .el-select {
    flex: 1;
  }
}

</style>
